package com.richard.base.net.model.repository

import com.richard.base.net.common.NetComponent
import com.richard.base.net.exception.ApiException
import com.richard.base.net.model.api.KsRetrofitClient
import com.richard.base.net.api.BaseRepository
import com.richard.base.common.loge
import com.richard.base.net.bean.KsResponse
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 ***************************************
 * 项目名称:base
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2019/12/31     11:28 AM
 * 用途:业务级别的 基础网络仓库
 * 想替换baseUrl ，override baseUrl（）方法即可
 ***************************************

 */
open class KsBaseRepository : BaseRepository() {
    private val TAG = "KsBaseRepository"

    override suspend fun <T> handleCode(response: KsResponse<T>): Any {
        return when (correctCode(response)) {
            -1 -> {//与后台开发商定，code=-1，我们需要toast
                //切换到主线程 toast
//                withContext(Dispatchers.Main) {
//                    NetComponent.tokenCallback.showToast(correctMessage(response))
//                }

                ApiException(correctCode(response), correctMessage(response))
            }
            0 -> response //正常数据，直接返回
            1002, 4002, 4001 -> //重新登录
            {
//                val block: suspend CoroutineScope.() -> Unit = {
//                    NetComponent.tokenCallback.reLogin(correctMessage(response))
//                }
//                withContext(Dispatchers.Main, block)
                "handleCode: 重新登录${correctCode(response)}".loge()
                ApiException(correctCode(response), correctMessage(response))
            }

            4003, 1001 -> //token 非法 ,刷新token
            {
                "${correctCode(response)} handleCode: 刷新token run in Thread ${Thread.currentThread().name}".loge()
//                val needRetry = NetComponent.tokenCallback.refreshToken()

                ApiException(code = correctCode(response), needRetry = false)
            }

            1009 -> // 绑定手机号
            {
//                withContext(Dispatchers.Main) {
//                    NetComponent.tokenCallback.bindMobile(correctMessage(response))
//                }
                "${correctCode(response)} handleCode: ".loge()
                ApiException(correctCode(response), correctMessage(response))
            }
            4024, 4025, 4030 ->  //账号出现问题
            {
//                NetComponent.loginCallback.handleLoginCode(correctCode(response))

                ApiException(correctCode(response), correctMessage(response))
            }
            else -> {
                "${correctCode(response)} handleCode: ".loge()
                response
            }
        }
    }

    fun <S> getService(clazz: Class<S>): S = KsRetrofitClient.getService(clazz)

}